/***
 *  Copyright (c) 2020 murenchao
 *  Flowing is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2. 
 *  You may obtain a copy of Mulan PSL v2 at:
 *           http://license.coscl.org.cn/MulanPSL2 
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
 *  See the Mulan PSL v2 for more details. 
 */
package cool.taomu.web;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.websocket.server.WsSci;

import cool.taomu.web.controller.DemoConteroller;
import cool.taomu.web.core.WebSocketServer;
import jakarta.servlet.ServletException;

/**
 * @author rcmu
 */
public class WebApplication {
    private static String PROJECT_PATH = System.getProperty("user.dir");
    private static String WEB_APP_PATH = PROJECT_PATH + File.separatorChar + "WebRoot";
    private static String CATALINA_HOME = PROJECT_PATH + "/Embedded/Tomcat";
    private Tomcat tomcat = new Tomcat();
    
    private int port;

    public WebApplication(int port) {
        this.port = port;
    }

    public void start2() throws LifecycleException, ServletException {
        tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.setBaseDir(CATALINA_HOME);

        Context context = tomcat.addWebapp("/fig", WEB_APP_PATH);

        Tomcat.addServlet(context,"demoServlet", new DemoConteroller());
        context.addServletMappingDecoded("/servlet", "demoServlet");
        tomcat.getConnector().setURIEncoding("UTF-8");

        context = tomcat.addContext("/fig/ws", WEB_APP_PATH);
        Set<Class<?>> classes = new HashSet<>();
        classes.add(WebSocketServer.class);
        context.addServletContainerInitializer(new WsSci(),classes);
        Tomcat.addServlet(context, "websocket", new DemoConteroller());
        context.addServletMappingDecoded("/socket", "websocket"); 

        tomcat.start();
        tomcat.getServer().await();
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return this.port;
    }

    public static void main(String[] args) throws Exception {
        if (args.length > 0) {
            if (args[0].equals("-c")) {
            }
        }
        WebApplication embededTomcat = new WebApplication(9310);
        embededTomcat.start2();
    }

}